<template>
  <div id="app">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"/>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>

<script>
import { wxAuth } from "@/utils/wx-auth";
import { getAuthUrl, getUserInfo, getWxConfig } from "@/api/wx";
import { searchToObj } from "@/utils/func";

export default {
  data() {
    return {};
  },
  async created() {
    let redirectUrl = await getAuthUrl();
    const searchObj = searchToObj(window.location.search);
    await this.initConfig();
    await this.handleWxAuth(searchObj, redirectUrl);
  },
  methods: {
    //微信授权逻辑处理
    async handleWxAuth(searchObj, redirectUrl) {
      let isAuth = localStorage.getItem("isAuth");
      if (searchObj && searchObj.code && !isAuth) {
        let res = await getUserInfo({ code: searchObj.code });
        localStorage.setItem("isAuth", 1);
        isAuth = 1;
        localStorage.setItem("userInfo", JSON.stringify(res.userInfo));
        localStorage.setItem("token", res.__token);
      }
      if (!isAuth) {
        //判断是否为签到页面
        if (window.location.href.indexOf("/signIn") > -1) {
          localStorage.setItem("isFromSignIn", 1);
        }
        wxAuth(redirectUrl);
      }
    },
    //微信-h5分享配置
    async initConfig() {
      // appId, timestamp, nonceStr, signature
      let res = await getWxConfig({ url: window.location.href });
      if (res) {
        let { appId, timestamp, nonceStr, signature } = res;
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appId, // 必填，公众号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature, // 必填，签名
          jsApiList: [
            "updateAppMessageShareData", //分享到微信及QQ（新接口）
            "updateTimelineShareData", //分享到朋友圈”及“分享到QQ空间（新接口）
            "onMenuShareAppMessage", //分享给微信朋友
            "onMenuShareTimeline", //分享到微信朋友圈
          ], // 必填，需要使用的JS接口列表
        });
      }
    },
  },
};
</script>

<style lang="scss">
@import url("global/style.scss");
html {
  height: 100%;
  width: 100%;
}
body {
  height: 100%;
  width: 100%;
  margin: 0;
  background: #f1f1f1;
}
#app {
  height: 100%;
  width: 100%;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  font-size: 16px;
}
</style>
